/*
 *    Copyright (c) 2018-2025, st All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: st
 */

package com.mkh.st.auth.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mkh.st.admin.api.dto.SysLogDTO;
import com.mkh.st.admin.api.dto.UserLockDTO;
import com.mkh.st.admin.api.feign.ISysLogProvider;
import com.mkh.st.admin.api.feign.ISysUserProvider;
import com.mkh.st.admin.api.vo.UserTenantVO;
import com.mkh.st.common.core.constant.CommonConstants;
import com.mkh.st.common.core.constant.enums.UserStatusEnum;
import com.mkh.st.common.core.util.KeyStrResolver;
import com.mkh.st.common.core.util.WebUtils;
import com.mkh.st.common.data.datascope.RedisUtil;
import com.mkh.st.common.log.util.LogTypeEnum;
import com.mkh.st.common.log.util.SysLogUtils;
import com.mkh.st.common.security.handler.AuthenticationFailureHandler;
import com.mkh.st.common.security.service.UserContext;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

/**
 * @author st
 * @date 2018/10/8
 */
@Slf4j
@Component
@AllArgsConstructor
public class DaoismAuthenticationFailureEventHandler implements AuthenticationFailureHandler {

	private final ISysLogProvider sysLogProvider;

	private final KeyStrResolver tenantKeyStrResolver;

	private final ISysUserProvider sysUserProvider;


	/**
	 * 异步处理，登录失败方法
	 * <p>
	 * @param authenticationException 登录的authentication 对象
	 * @param authentication 登录的authenticationException 对象
	 * @param request 请求
	 * @param response 响应
	 */
	@Async
	@Override
	@SneakyThrows
	public void handle(AuthenticationException authenticationException, Authentication authentication,
			HttpServletRequest request, HttpServletResponse response) {
		String username = authentication.getName();
		SysLogDTO sysLog = SysLogUtils.getSysLog(request, username);
		sysLog.setTitle(username + "用户登录");
		sysLog.setType(LogTypeEnum.ERROR.getType());
		sysLog.setParams(username);
		sysLog.setException(authenticationException.getLocalizedMessage());
		String header = request.getHeader(HttpHeaders.AUTHORIZATION);
		sysLog.setServiceId(WebUtils.extractClientId(header).orElse("N/A"));
		sysLog.setTenantId(Long.valueOf(tenantKeyStrResolver.key()));
		sysLogProvider.saveLog(sysLog);
		//密码错误统计失败次数
		if(authenticationException instanceof BadCredentialsException){
			Object errorCount=RedisUtil.get(username+ CommonConstants.PASSWORD_ERROR_COUNT);
			LocalDateTime beginTime=LocalDateTime.now();
			LocalDateTime endTime= beginTime.withHour(23).withMinute(59).withSecond(59);
			Long expire=LocalDateTimeUtil.between(beginTime,endTime, ChronoUnit.SECONDS);
			if(ObjectUtil.isNull(errorCount)){
				RedisUtil.set(username+CommonConstants.PASSWORD_ERROR_COUNT,CommonConstants.ONE,expire);
			}else {
				int count=Integer.parseInt(errorCount.toString());
				//失败次数达到5次锁定账号
				if(count >= CommonConstants.MAX_ERROR_COUNT){
					UserLockDTO dto=new UserLockDTO(username, UserStatusEnum.LOCK.getStatus());
					//账号锁定后删除失败次数缓存
					sysUserProvider.lockUserStatus(dto);
					RedisUtil.del(username+CommonConstants.PASSWORD_ERROR_COUNT);
				}else {//不到5次继续累加
					count++;
					RedisUtil.set(username+CommonConstants.PASSWORD_ERROR_COUNT,count,expire);
				}
			}
		}
		UserContext.remove();
		log.info("用户：{} 登录失败，异常：{}", username, authenticationException.getLocalizedMessage());
	}

}
